<script setup>
import { User, Lock, Message, Key } from '@element-plus/icons-vue'
import {reactive, ref} from 'vue'
import MyRouter from "@/router/RouterTable";
import { ElMessage, ElNotification } from "element-plus";
import axios from "axios";

const activeName = ref('account')
const loginForm = ref(null)

const state = reactive({
  ruleForm: {
    username: '',
    account: '',
    password: '',
    rePassword: ''
  },
  checked: true,
  rules: {
    username: [
      { required: 'true', message: '用户名不能为空', trigger: 'blur' },
      { max: 5, min: 2, message: "用户名长度范围应在2-5之间" }
    ],
    account: [
      { required: 'true', message: '账号不能为空', trigger: 'blur' },
    ],
    password: [
      { required: 'true', message: '密码不能为空', trigger: 'blur' },
      { max: 9, min: 6, message: "密码长度范围应在6-9之间" }
    ],
    rePassword: [
      {
        validator: (rule, value, callback) => {
          if (info.data.userRegRepeatPwd !== info.data.userRegPwd) {
            callback(new Error('两次输入的密码不一致'));
          } else {
            callback(); // 没有错误时调用callback()
          }
        },
        trigger: 'blur' // 当字段失去焦点时触发验证
      }
    ]
  }
})

const info = reactive({
  data:{
    userAccount: "",
    userName: "",
    userPwd: "",
    userRegPwd: "",
    userRegRepeatPwd: "",
    userEmail: "",
    code: ""
  }
})

/** 登录函数 **/
function login() {
  axios({
    method:"GET",
    url:"http://localhost:8080/boot/user/login",
    params:{
      userAccount: info.data.userAccount,
      userPwd: info.data.userPwd,
    }
  }).then((result) => {
    if(result.data === 'success'){
      MyRouter.push("/layout/userIndex");
      ElMessage({
        message:"登录成功",
        type:"success",
      })
    }else{
      ElMessage.error("账号或密码错误！")
    }
  })
}

const code = ref("")
// 发送验证码
function sendEmail() {
  axios({
    method: "POST",
    url: "http://localhost:8080/boot/user/sendEmail",
    params: {
      email: info.data.userEmail
    }
  })
      .then((result) => {
        if (result.data === 'none') {
          ElMessage({
            message:"该邮箱不存在，请先注册",
            type:"error",
          })
        } else {
          ElMessage({
            message:"验证码已发送，请注意查收",
            type:"success",
          })

          code.value = result.data
        }
      })
}

// 邮箱登录
function emailLogin() {
  axios({
    method: "GET",
    url: "http://localhost:8080/boot/user/emailLogin",
    params: {
      emailCode: info.data.code
    }
  })
      .then((result) => {
        if (result.data.userAccount === "error") {
          ElMessage({
            message:"验证码错误，请重试",
            type:"error",
          })
        } else {
          info.data.userAccount = result.data.userAccount
          info.data.userPwd = result.data.userPwd

          login()
        }
      })
}

function register() {
  axios({
    method: "POST",
    url: "http://localhost:8080/boot/user/createUser",
    params: {
      userName: info.data.userName,
      userPwd: info.data.userRegPwd
    }
  })
      .then((result) => {
        ElNotification({
          title: '注册成功',
          message: '这是您申请的账号，请牢记：'+result.data,
          duration: 0,
          type: "success",
          offset: 100
        })
      })
      .catch((error) => {
        // 处理请求失败的情况
        ElNotification({
          title: '注册失败',
          message: error.message || '注册时发生未知错误',
          type: "error",
          offset: 100
        });
        console.error('注册失败:', error); // 在控制台中记录错误
      });
}

</script>

<template>
  <div class="login-body">
    <div class="login-container">
      <div class="head" style="position: relative; left: 1%; top: 0">
        <div class="name">
          <div class="title">保险业务管理系统</div>
          <br>
          <div class="tips">By Group 7</div>
        </div>
      </div>
      <div style="position: relative; top: -3%">
        <el-tabs v-model="activeName" class="demo-tabs" tab-position="top" stretch>
          <el-tab-pane label="系统账号" name="account">
            <br>
            <el-form label-position="top" :rules="state.rules" :model="state.ruleForm" ref="loginForm" class="login-form">
              <el-form-item prop="account">
                <el-input
                    v-model="info.data.userAccount"
                    type="text"
                    size="large"
                    v-model.trim="state.ruleForm.account"
                    autocomplete="off"
                    clearable
                    placeholder="请输入账号"
                    :prefix-icon="User"
                />
              </el-form-item>
              <br>
              <el-form-item prop="password">
                <el-input
                    type="password"
                    size="large"
                    v-model="info.data.userPwd"
                    v-model.trim="state.ruleForm.password"
                    autocomplete="off"
                    show-password
                    placeholder="请输入密码"
                    :prefix-icon="Lock"
                />
              </el-form-item>
              <el-form-item>
                <br>
                <el-button type="primary" round style="width: 300px;font-weight: bold" @click="login">登录</el-button>
                <br>
                <br>
                <br>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="邮箱" name="email">
            <br>
            <el-form label-position="top" ref="loginForm" class="login-form">
              <el-form-item prop="email">
                <el-input
                    v-model="info.data.userEmail"
                    type="text"
                    size="large"
                    v-model.trim="state.ruleForm.account"
                    autocomplete="off"
                    clearable
                    placeholder="请输入邮箱"
                    :prefix-icon="Message"
                />
              </el-form-item>
              <br>
              <el-form-item prop="code">
                <el-input
                    type="text"
                    size="large"
                    v-model="info.data.code"
                    v-model.trim="state.ruleForm.password"
                    autocomplete="off"
                    placeholder="请输入验证码"
                    :prefix-icon="Key"
                />
              </el-form-item>
              <el-form-item>
                <br>
                <el-button type="primary" round style="width: 300px;font-weight: bold" @click="sendEmail">获取验证码</el-button>
                <br>
                <el-button type="primary" round style="width: 300px;font-weight: bold" @click="emailLogin">登录</el-button>
                <br>
                <br>
                <br>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="注册" name="register">
            <br>
            <el-form label-position="top" :rules="state.rules" :model="state.ruleForm" ref="loginForm" class="login-form">
              <el-form-item prop="username">
                <el-input
                    v-model="info.data.userName"
                    type="text"
                    size="large"
                    v-model.trim="state.ruleForm.username"
                    autocomplete="off"
                    clearable
                    placeholder="请输入用户名"
                    :prefix-icon="User"
                />
              </el-form-item>
              <br>
              <el-form-item prop="password">
                <el-input
                    v-model="info.data.userRegPwd"
                    :prefix-icon="Lock"
                    type="password"
                    placeholder="请输入密码"
                    size="large"
                    v-model.trim="state.ruleForm.password"
                    autocomplete="off"
                    show-password
                >
                </el-input>
              </el-form-item>
              <br>
              <el-form-item prop="rePassword">
                <el-input
                    v-model="info.data.userRegRepeatPwd"
                    :prefix-icon="Lock"
                    type="password"
                    placeholder="请再次输入密码"
                    size="large"
                    v-model.trim="state.ruleForm.password"
                    autocomplete="off"
                    show-password
                >
                </el-input>
              </el-form-item>
              <!-- 注册按钮 -->
              <el-form-item>
                <br>
                <el-button type="primary" round style="width: 300px;font-weight: bold" @click="register">注册</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<style  scoped>
/* 样式 */
.login-body {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 99%;
  height: 98%;
  position: absolute;
  top: 1%;

  background-image: url("../../assets/bg.jpg");
  background-repeat: repeat;
}

.login-container {
  width: 420px;
  height: 500px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 21px 41px 0 rgba(0, 0, 0, 0.2);
}
.head {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 0 20px 0;
}
.head img {
  width: 100px;
  height: 100px;
  margin-right: 20px;
}
.head .title {
  font-size: 28px;
  color: #3497e3;
  font-weight: bold;
}
.head .tips {
  font-size: 20px;
  color: #999;
  font-weight: bold;
}
.login-form {
  width: 70%;
  margin: 0 auto;
}
.login-form >>> .el-form--label-top .el-form-item__label {
  padding: 0;
}
.login-form >>> .el-form-item {
  margin-bottom: 0;
}
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
</style>
